import sys, os
base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_path)
from pika.channel import Channel
from redis import StrictRedis
import pika
from pika import PlainCredentials
from pika.connection import Connection
from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime
from tools.spider.spider import get_hot
from tools.spider.const import HOT_DICT

EMAIL_PREFIX = 'pytools:user:email'
HOT_INFO_PREFIX = 'pytools:info:'

# redis缓存
redis_client: StrictRedis = StrictRedis(host='1.15.170.222', port='6379')

# RabbitMQ的链接认证
auth: PlainCredentials = PlainCredentials(username='guest', password='guest')

connet_parameter: pika.ConnectionParameters = pika.ConnectionParameters(
    host='1.15.170.222', port='5672', virtual_host='/', credentials=auth)

# 发送邮箱到RabbitMq
def send_email_to_rabbit():
    emails = redis_client.lrange(EMAIL_PREFIX, 0, -1)
    connection: Connection = pika.BlockingConnection(connet_parameter)
    channel: Channel = connection.channel()
    for email in emails:
        channel.basic_publish(exchange='pytools.system.direct', 
                              routing_key='email',
                              body=email)
        print(f'{email}邮箱信息已经发送')
    channel.close()
    print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), ", 发送完成")

# 定时获取热搜信息放到redis上
def get_info_to_redis():
    for key, value in HOT_DICT.items():
        response = get_hot(value)
        redis_client.set(HOT_INFO_PREFIX + key, response)
        redis_client.persist(HOT_INFO_PREFIX + key)
        
        print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), ", 爬取完成===>", key)





# 获取一个调度器
scheduler = BlockingScheduler(timezone='Asia/Shanghai')

# 启动定时任务

# 定时发送邮件
scheduler.add_job(send_email_to_rabbit, 'cron', day_of_week='*', hour=11, minute=20)

# scheduler.add_job(send_email_to_rabbit, 'interval', minutes=1)


# 定时爬取
scheduler.add_job(get_info_to_redis, 'interval', minutes=3)

# 启动调度器
scheduler.start()